import 'dart:io';
import 'dart:convert';

import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:http_parser/http_parser.dart';
import 'package:get/get.dart' hide MultipartFile, FormData;
import 'package:image_picker/image_picker.dart';
import "package:flutter_screenutil/flutter_screenutil.dart";
import 'package:yinshui_caiying/http/api_base.dart';
import 'package:yinshui_caiying/http/api_water.dart';
import 'package:yinshui_caiying/model/image_model.dart';
import 'package:yinshui_caiying/model/image_result_model.dart';
import 'package:yinshui_caiying/model/baidu_number_result.dart';
import 'package:yinshui_caiying/model/baidu_error_result.dart';
import 'package:yinshui_caiying/model/baidu_identityCard_result.dart';
import 'package:yinshui_caiying/model/params_model.dart';
import 'package:yinshui_caiying/model/result_model.dart';
import 'package:yinshui_caiying/model/water_type_model.dart';
import 'package:yinshui_caiying/pages/water/water_user_list.dart';
import 'package:yinshui_caiying/services/common_services.dart';
import 'package:yinshui_caiying/services/baidu_error_code.dart';
import 'package:yinshui_caiying/utils/ImageCompressUtil.dart';
import 'package:yinshui_caiying/utils/colors.dart';
import 'package:yinshui_caiying/http/http.dart';
import 'package:yinshui_caiying/utils/inputformatter.dart';
import 'package:yinshui_caiying/widgets/appbar.dart';
import 'package:yinshui_caiying/widgets/base_scaffold.dart';
import 'package:yinshui_caiying/widgets/form/form_with_number.dart';
import 'package:yinshui_caiying/widgets/form/form_with_singlePicker.dart';
import 'package:yinshui_caiying/widgets/form/form_with_textField.dart';
import 'package:yinshui_caiying/widgets/form/form_with_radio.dart';
import 'package:yinshui_caiying/widgets/form/form_with_textArea.dart';
import 'package:yinshui_caiying/widgets/form/form_with_adPicker.dart';
import 'package:yinshui_caiying/widgets/modal_title.dart';
import 'package:yinshui_caiying/widgets/my_dialog.dart';
import 'package:yinshui_caiying/widgets/picker/models/ad_list_result_model.dart';
import 'package:yinshui_caiying/widgets/picker/models/pickerItem_model.dart';
import 'package:yinshui_caiying/widgets/picker/pickers.dart';

class CollectionPage extends StatelessWidget {
  CollectionPageController vm = Get.put(CollectionPageController());
  CommonService commonService = Get.find();
  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
        appBar: BackTitleBar(title: '信息采集'),
        body: Container(
            width: 1.sw,
            decoration: BoxDecoration(color: Color.fromRGBO(240, 242, 245, 1)),
            child: SingleChildScrollView(
                child: Column(children: [
              menuBar(context),
              Container(
                  width: 1.sw,
                  decoration: BoxDecoration(color: Colors.white),
                  child: Column(children: [
                    titleBar(context),
                    stepperBar(),
                    imgBox(),
                    GetBuilder<CollectionPageController>(
                        id: 'step12',
                        builder: (_) {
                          if (vm.activeStep.value == '1') {
                            return stepsBase(
                                '基表号识别', '基表号', vm.tableNum, vm.tableImgPath);
                          } else if (vm.activeStep.value == '2' &&
                              vm.meterType.value.value == '2') {
                            return stepsBase(
                                '采集终端ID识别', 'ID', vm.baseNum, vm.baseImgPath);
                          } else {
                            return Container();
                          }
                        }),
                    GetBuilder<CollectionPageController>(
                        id: 'step1',
                        builder: (_) {
                          if (_.activeStep.value == '1') {
                            return Container(
                                width: 1.sw,
                                margin: EdgeInsets.only(top: 100.h),
                                decoration: BoxDecoration(
                                    border: Border(
                                        top: BorderSide(
                                            width: 29.h,
                                            color: Color.fromRGBO(
                                                240, 242, 245, 1)))),
                                child: Container(
                                    width: 1.sw,
                                    padding: EdgeInsets.only(
                                        left: 74.w, right: 75.w),
                                    child: Column(
                                      children: [
                                        FormInput(
                                            title: '水表底数',
                                            hasBorder: true,
                                            initValue: vm.initNum.value,
                                            placeholder: '输入基表表盘示数',
                                            keyboardType: TextInputType.number,
                                            inputFormatters: [
                                              InputFormatter.xiaoshu
                                            ],
                                            onChanged: (value) {
                                              vm.initNum.value = value;
                                            }),
                                        SizedBox(
                                          height: 20.h,
                                        ),
                                        FormInput(
                                            title: '水表通径',
                                            hasBorder: false,
                                            initValue: vm.initNum1.value,
                                            placeholder: '输入水表通径(mm)',
                                            keyboardType: TextInputType.number,
                                            inputFormatters: [
                                              InputFormatter.xiaoshu
                                            ],
                                            unit: 'mm',
                                            onChanged: (value) {
                                              vm.initNum1.value = value;
                                            }),
                                      ],
                                    )));
                          } else if ((_.activeStep.value == '2' &&
                                  vm.meterType.value.value == '1') ||
                              _.activeStep.value == '3') {
                            return stepsThree(context);
                          } else {
                            return Container();
                          }
                        }),
                    Obx(() {
                      int neststeps = int.parse(vm.activeStep.value) + 1;

                      ///两种情况，分体式和一体式
                      ///分体式
                      if (vm.meterType.value.value == '2') {
                        if (vm.activeStep.value == '1' &&
                            vm.tableNum.value != '') {
                          return nextBtn(neststeps);
                        } else if (vm.activeStep.value == '2' &&
                            vm.baseNum.value != '') {
                          return nextBtn(neststeps);
                        } else {
                          return Container();
                        }
                      } else {
                        ///一体式
                        if (vm.activeStep.value == '1' &&
                            vm.tableNum.value != '') {
                          return nextBtn(neststeps);
                        } else {
                          return Container();
                        }
                      }
                    }),
                  ]))
            ]))));
  }

  Widget imgBox() {
    return Obx(() {
      switch (vm.activeStep.value) {
        case '1':
          return Obx(() {
            if (vm.tableImgPath.value != '') {
              return GestureDetector(
                onTap: () {
                  MyDialog.openImageView(0, vm.imageList);
                },
                child: Container(
                  width: 0.9.sw,
                  height: 200,
                  child: Image.network(vm.tableImgPath.value),
                ),
              );
            } else {
              return Container();
            }
          });
        case '2':
          return Obx(() {
            if (vm.baseImgPath.value != '') {
              return GestureDetector(
                onTap: () {
                  MyDialog.openImageView(1, vm.imageList);
                },
                child: Container(
                  width: 0.9.sw,
                  height: 200,
                  child: Image.network(vm.baseImgPath.value),
                ),
              );
            } else {
              return Container();
            }
          });
        case '3':
          return Obx(() {
            if (vm.identityCardImgPath.value != '') {
              return GestureDetector(
                onTap: () {
                  MyDialog.openImageView(2, vm.imageList);
                },
                child: Container(
                  width: 0.9.sw,
                  height: 200,
                  child: Image.network(vm.identityCardImgPath.value),
                ),
              );
            } else {
              return Container();
            }
          });
        default:
          return Container();
      }
    });
  }

  ///水表类型选择器
  Widget menuBar(BuildContext context) {
    return Container(
      width: 1.sw,
      height: 140.h,
      decoration: BoxDecoration(color: Colors.white),
      child: menuItem(context, '水表类型', vm.meterType, vm.meterTypePicker),
    );
  }

  Widget menuItem(
    BuildContext context,
    String title,
    Rx<PickerItemModel> value,
    dynamic Function(BuildContext, String) onPressed,
  ) {
    return TextButton(
      onPressed: onPressed(context, title),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Obx(() => Text(
                value.value.name,
                overflow: TextOverflow.fade,
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 42.sp,
                  fontWeight: FontWeight.w400,
                  fontFamily: "PingFang SC",
                ),
              )),
          Container(
              width: 50.w,
              margin: EdgeInsets.only(left: 24.w),
              child: Icon(
                Icons.expand_more,
                color: Color.fromRGBO(204, 204, 204, 1),
                size: 42.sp,
              ))
        ],
      ),
    );
  }

  Widget titleBar(BuildContext context) {
    return Container(
      width: 1.sw,
      padding: EdgeInsets.only(top: 64.h, bottom: 60.h),
      margin: EdgeInsets.only(bottom: 142.h),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
              top: BorderSide(
                  width: 30.h, color: Color.fromRGBO(240, 242, 245, 1))),
          boxShadow: [
            //卡片阴影
            BoxShadow(
                color: Color.fromRGBO(6, 0, 1, 0.08),
                offset: Offset(0, 40.h),
                blurRadius: 40.h)
          ]),
      child: Text(
        vm.projectInfoName + '信息采集',
        textAlign: TextAlign.center,
        style: TextStyle(
            color: Colors.black, fontSize: 52.sp, fontWeight: FontWeight.w500),
      ),
    );
  }

  Widget stepperBar() {
    return Container(
        width: 1.sw,
        padding: EdgeInsets.only(left: 75.w, right: 75.w),
        child: GetBuilder<CollectionPageController>(
            id: 'tableType',
            builder: (_) {
              if (_.meterType.value.value == '1') {
                return Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      stepItem1('1', '基表号识别'),
                      // stepItem('2', '采集终端ID识别'),
                      stepItem1('2', '用户信息识别')
                    ]);
              } else {
                return Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      stepItem2('1', '基表号识别'),
                      stepItem2('2', '采集终端ID识别'),
                      stepItem2('3', '用户信息识别')
                    ]);
              }
            }));
  }

  Widget stepItem1(String steps, String title) {
    return Obx(() => Expanded(
        flex: 1,
        child: Stack(alignment: Alignment.center, children: <Widget>[
          Positioned(
              width: 1.sw,
              left: 0,
              top: 60.h,
              child: Container(
                  width: 1.sw - 150.w,
                  height: 1,
                  child: LinearProgressIndicator(
                      value: vm.activeStep.value == steps ? 1 : 0,
                      backgroundColor: Color.fromRGBO(210, 209, 214, 1),
                      valueColor:
                          AlwaysStoppedAnimation<Color>(MyColors.main)))),
          Column(children: [
            MaterialButton(
                minWidth: 119.w,
                height: 119.h,
                padding: EdgeInsets.all(0),
                color: vm.activeStep.value == steps
                    ? MyColors.main
                    : Color.fromRGBO(242, 242, 242, 1),
                onPressed: () {
                  FocusManager.instance.primaryFocus!.unfocus();
                  if (int.parse(steps) < int.parse(vm.activeStep.value)) {
                    vm.activeStep.value = steps.toString();
                    vm.update(['step1']);
                    vm.update(['step12']);
                  }
                },
                child: Text(steps,
                    style: TextStyle(
                      color: vm.activeStep.value == steps
                          ? Colors.white
                          : Color.fromRGBO(51, 51, 51, 1),
                      fontSize: 52.sp,
                      fontStyle: FontStyle.italic,
                      fontWeight: FontWeight.w500,
                      fontFamily: "PingFang SC",
                    )),
                shape: CircleBorder()),
            Text(title,
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
                style: TextStyle(
                    height: 2.5,
                    color: vm.activeStep.value == steps
                        ? MyColors.main
                        : Color.fromRGBO(102, 102, 102, 1),
                    fontSize: 36.sp,
                    fontWeight: FontWeight.w400,
                    fontFamily: "PingFang SC"))
          ]),
        ])));
  }

  Widget stepItem2(String steps, String title) {
    return Obx(() => Expanded(
        flex: 1,
        child: Stack(alignment: Alignment.center, children: <Widget>[
          Positioned(
              width: 1.sw,
              left: 0,
              top: 60.h,
              child: Container(
                  width: 1.sw - 150.w,
                  height: 1,
                  child: LinearProgressIndicator(
                      value: vm.activeStep.value == steps ? 1 : 0,
                      backgroundColor: Color.fromRGBO(210, 209, 214, 1),
                      valueColor:
                          AlwaysStoppedAnimation<Color>(MyColors.main)))),
          Column(children: [
            MaterialButton(
                minWidth: 119.w,
                height: 119.h,
                padding: EdgeInsets.all(0),
                color: vm.activeStep.value == steps
                    ? MyColors.main
                    : Color.fromRGBO(242, 242, 242, 1),
                onPressed: () {
                  FocusManager.instance.primaryFocus!.unfocus();
                  if (int.parse(steps) < int.parse(vm.activeStep.value)) {
                    vm.activeStep.value = steps.toString();
                    vm.update(['step1']);
                    vm.update(['step12']);
                  }
                },
                child: Text(steps,
                    style: TextStyle(
                      color: vm.activeStep.value == steps
                          ? Colors.white
                          : Color.fromRGBO(51, 51, 51, 1),
                      fontSize: 52.sp,
                      fontStyle: FontStyle.italic,
                      fontWeight: FontWeight.w500,
                      fontFamily: "PingFang SC",
                    )),
                shape: CircleBorder()),
            Text(title,
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
                style: TextStyle(
                    height: 2.5,
                    color: vm.activeStep.value == steps
                        ? MyColors.main
                        : Color.fromRGBO(102, 102, 102, 1),
                    fontSize: 36.sp,
                    fontWeight: FontWeight.w400,
                    fontFamily: "PingFang SC"))
          ]),
        ])));
  }

/* steps 1 / steps 2*/
  Widget stepsBase(String btnText, String numText, Rx<String> numValue,
      Rx<String> imagePath) {
    var neststeps = int.parse(vm.activeStep.value) + 1;
    return Column(
      children: [
        collectBtn(btnText),
        collectText(),
        GetBuilder<CollectionPageController>(
            id: 'stepImage',
            builder: (_) {
              if (imagePath.value != "") {
                return Container(
                  padding: EdgeInsets.only(left: 100.w, right: 100.w),
                  child: Row(
                    children: [
                      Text(
                        numText,
                        style: TextStyle(
                            height: 1.9,
                            fontSize: 58.sp,
                            fontWeight: FontWeight.w500,
                            color: Color.fromRGBO(254, 108, 1, 1),
                            fontFamily: "PingFang SC"),
                      ),
                      SizedBox(
                        width: 50.w,
                      ),
                      Expanded(
                          child: TextFormField(
                              onChanged: (value) {
                                numValue.value = value;
                              },
                              style: TextStyle(
                                  height: 1.9,
                                  fontSize: 58.sp,
                                  fontWeight: FontWeight.w500,
                                  color: Color.fromRGBO(254, 108, 1, 1),
                                  fontFamily: "PingFang SC"),
                              textAlign: TextAlign.right,
                              controller:
                                  TextEditingController(text: numValue.value),
                              keyboardType: TextInputType.number,
                              decoration: InputDecoration(
                                border: InputBorder.none,
                                isDense: true,
                              )))
                    ],
                  ),
                );
              } else {
                return Container();
              }
            }),
      ],
    );
  }

/* steps 3 */
  Widget stepsThree(BuildContext context) {
    return Column(
      children: [
        collectBtn('用户身份证识别'),
        collectText(),
        userId(),
        userInfo(context)
      ],
    );
  }

/* step3 user id */
  Widget userId() {
    return Container(
        width: 1.sw,
        padding:
            EdgeInsets.only(top: 30.h, left: 74.w, right: 60.w, bottom: 30.h),
        child: Obx(() =>
            Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              stepsThreeTitle('识别结果', true),
              stepsThreeText('基表号：', vm.tableNum.value),
              stepsThreeText('水表底数：', vm.initNum.value),
              stepsThreeText('水表通径：', vm.initNum1.value),
              vm.meterType.value.value == '2'
                  ? stepsThreeText('采集终端ID：', vm.baseNum.value)
                  : Container(),
              stepsThreeText('姓名：', vm.username.value),
              stepsThreeText('身份证号：', vm.identityCard.value),
              stepsThreeText('住址：', vm.address.value),
            ])));
  }

  /* step3 title */
  Widget stepsThreeTitle(String title, bool hasEdit) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(title,
            style: TextStyle(
                color: MyColors.main,
                fontSize: 46.sp,
                fontWeight: FontWeight.w500,
                fontFamily: "PingFang SC")),
        hasEdit
            ? IconButton(
                icon: Icon(
                  Icons.border_color,
                  color: MyColors.main,
                  size: 42.sp,
                ),
                onPressed: () {
                  vm.openUserInfoEditPicker();
                })
            : Container()
      ],
    );
  }

/* step3 user id text */
  Widget stepsThreeText(String title, String value) {
    return Text(title + value,
        style: TextStyle(
            height: 2.2,
            color: Color.fromRGBO(96, 96, 96, 1),
            fontSize: 36.sp,
            fontWeight: FontWeight.w400,
            fontFamily: "PingFang SC"));
  }

/* step3 user info */
  Widget userInfo(BuildContext context) {
    return Container(
        width: 1.sw,
        decoration: BoxDecoration(
            border: Border(
                top: BorderSide(
          width: 30.h,
          color: Color.fromRGBO(240, 242, 245, 1),
        ))),
        margin: EdgeInsets.only(top: 35.h),
        padding: EdgeInsets.only(top: 40.h, left: 74.w, right: 60.w),
        child: Form(
            key: vm._formKey, //设置globalKey，用于后面获取FormState
            child:
                Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              stepsThreeTitle('用水户信息完善', false),
              // FormAdPicker(
              //     title: '归属地',
              //     onConfirm: vm.adIdCof,
              //     dataList: vm.commonService.adList,
              //     name: vm.adName,
              //     value: vm.adId),
              FormSinglePicker(
                  title: '用水类型',
                  onConfirm: vm.waterTypeCof,
                  dataList: vm.waterTypeList,
                  value: vm.waterType),
              FormInput(
                title: '手机号',
                request: true,
                placeholder: '请输手机号码',
                keyboardType: TextInputType.phone,
                onChanged: (value) {
                  vm.phone.value = value;
                },
              ),
              FormNumber(
                title: '用水人口',
                controller:
                    TextEditingController(text: vm.familySize.value.toString()),
                request: true,
                placeholder: '请输用水人口',
                onChanged: (value) {
                  vm.familySize.value = NumUtil.getNumByValueDouble(
                      NumUtil.getDoubleByValueStr(value), 0) as int;
                },
              ),
              FormRadio(
                title: '是否养殖',
                dataList: vm.breederList,
                groupValue: vm.isBreeder,
              ),
              Obx(() => vm.isBreeder.value == '1'
                  ? FormTextArea(
                      placeholder: '填写养殖信息',
                      request: true,
                      onChanged: (value) {
                        vm.breedNote.value = value;
                      },
                    )
                  : Container()),
              FormTextArea(
                title: '备注',
                placeholder: '填写备注信息',
                hasBorder: false,
                onChanged: (value) {
                  vm.note.value = value;
                },
              ),
              vm._saveButton()
            ])));
  }

  /* 采集按钮 */
  Widget collectBtn(String title) {
    return Container(
      width: 1.sw,
      margin: EdgeInsets.fromLTRB(72.w, 100.h, 69.w, 55.h),
      child: TextButton(
        style: ButtonStyle(
            shape: MaterialStateProperty.all(RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(4.sp))),
            padding: MaterialStateProperty.all(
                EdgeInsets.only(top: 20.h, bottom: 20.h)),
            backgroundColor: MaterialStateProperty.all(MyColors.main)),
        child: Text(title,
            style: TextStyle(
                fontSize: 58.sp,
                fontWeight: FontWeight.w500,
                color: Colors.white)),
        onPressed: () {
          ///取消焦点，优化体验
          FocusManager.instance.primaryFocus!.unfocus();
          vm.openImagePicker();
        },
      ),
    );
  }

  /* 采集按钮 */
  Widget nextBtn(int neststeps) {
    return Container(
      width: 1.sw,
      margin: EdgeInsets.fromLTRB(72.w, 10.h, 69.w, 55.h),
      child: TextButton(
        style: ButtonStyle(
            shape: MaterialStateProperty.all(RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(4.sp))),
            padding: MaterialStateProperty.all(
                EdgeInsets.only(top: 20.h, bottom: 20.h)),
            backgroundColor: MaterialStateProperty.all(MyColors.main)),
        child: Text('下一步',
            style: TextStyle(
                fontSize: 58.sp,
                fontWeight: FontWeight.w500,
                color: Colors.white)),
        onPressed: () {
          if (neststeps == 2 &&
              (vm.initNum.value == '' || vm.initNum1.value == '')) {
            SmartDialog.showToast('请填写水表底数和水表通径', alignment: Alignment.center);
          } else {
            vm.activeStep.value = neststeps.toString();
            vm.update(['step1']);
            vm.update(['step12']);
          }
        },
      ),
    );
  }

/* 采集拍照提示 */
  Widget collectText() {
    return Text('通过拍照或上传图片进行设备及用户信息获取',
        style: TextStyle(
            fontSize: 34.sp,
            fontWeight: FontWeight.w400,
            color: Color.fromRGBO(119, 119, 119, 0.6),
            fontFamily: "PingFang SC"));
  }

/* 公用字体样式 */
  Widget formTextStyles(String title) {
    return Text(
      title,
      style: TextStyle(
        color: Colors.black,
        fontSize: 40.sp,
        fontWeight: FontWeight.w400,
      ),
    );
  }
}

class CollectionPageController extends GetxController {
  CommonService commonService = Get.find();
  String projectInfoName = '';
  late int projectInfoId;
  /* 水表类型选择 */
  final meterType = PickerItemModel(name: "一体式水表", value: '1').obs;
  List<PickerItemModel> meterTypeList = [
    PickerItemModel(name: "一体式水表", value: '1'),
    PickerItemModel(name: "分体式水表", value: '2'),
  ].obs;
  /* 步骤 */
  var activeStep = '1'.obs;
  var tableNum = ''.obs; //水表号/基表号
  int tableImgId = 0; //水表号/基表号图片id
  ///水表号/基表号图片地址
  final tableImgPath = ''.obs;

  ///基表表盘示数
  final initNum = ''.obs; //水表基数

  ///水表通径
  final initNum1 = ''.obs;
  var baseNum = ''.obs; //采集终端号
  int baseImgId = 0; //采集终端号图片id
  ///采集终端号图片地址
  final baseImgPath = ''.obs;
  var username = ''.obs; //户名
  var identityCard = ''.obs; //身份证号
  int identityCardImgId = 0; //身份证号图片id
  ///身份证号图片地址
  final identityCardImgPath = ''.obs;
  var address = ''.obs; //详细地址
  final waterType = PickerItemModel().obs; //用水类型
  List<PickerItemModel> waterTypeList = []; //获用水类型列表
  var phone = ''.obs; //手机号
  var familySize = 1.obs; //用水人口
  final adId = Rx<int>(0); //归属地-id
  final adName = ''.obs; //归属地-名称
  final isBreeder = '0'.obs; //是否养殖
  var breedNote = ''.obs; //养殖说明
  var note = ''.obs; //备注
  List breederList = [
    {'name': "否", 'value': '0'},
    {'name': "是", 'value': '1'},
  ]; //是否养殖
  var baiduToken = ''; //百度TOKEN

  @override
  void onInit() {
    projectInfoName = Get.arguments.name;
    projectInfoId = Get.arguments.id;
    adId.value = Get.arguments.ad_id;
    getBaiduToken();
    _getWaterTypeList(adId.value);
    super.onInit();
  }

  _getWaterTypeList(int id) async {
    try {
      var res = await Http().post(ApiWater.WATER_PRICE_LIST, data: {
        "paginate": {"total": 0, "page": 1, "per_page": 20},
        "params": {"ad_id": id, "params": ""}
      });
      WaterTypeResultModel result = WaterTypeResultModel.fromJson(res);

      if (result.code == 200) {
        result.content.data.forEach((element) {
          waterTypeList.add(PickerItemModel(
              name: element.name,
              value: element.id.toString(),
              creditLevel: element.creditLevel));
        });
        waterType(waterTypeList[0]);
      } else {}
    } catch (e) {}
  }

  /* 水表类型选择器 */
  meterTypePicker(BuildContext context, String title) {
    return () {
      Pickers.showSinglePicker(
        data: meterTypeList,
        selectData: meterType.value,
        onConfirm: meterTypeCof,
      );
    };
  }

  /* 水表类型选择 */
  meterTypeCof(PickerItemModel value) {
    meterType(value);
    activeStep.value = '1';
    update(['tableType']);
    update(['step1']);
    update(['step12']);
    resetFormData();
  }

  ///重置表单数据
  resetFormData() {
    baseNum.value = '';
    initNum.value = '';
    identityCard.value = '';
    tableNum.value = '';
    tableImgId = 0;
    tableImgPath.value = '';
    baseImgPath.value = '';

    baseImgId = 0;
    identityCardImgId = 0;
    identityCardImgPath.value = '';
    imageList.clear();
    initNum1.value = '';
  }

  /*用水类型选择 */
  waterTypeCof(PickerItemModel value) {
    waterType(value);
  }

  /* 归属地选择 */
  adIdCof(List<AdItemModel> data) {
    adName.value = data.map((e) => e.name).toList().join('-');
    adId.value = data[data.length - 1].id;
    _getWaterTypeList(adId.value);
  }

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<FormState> _formKeyDetail = GlobalKey<FormState>();

  ///保存按钮
  _saveButton() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          width: 724.w,
          height: 145.h,
          margin: EdgeInsets.only(top: 30.h, bottom: 120.h),
          child: ElevatedButton(
            onPressed: () {
              if (_formKey.currentState!.validate() && _validateForm()) {
                _saveForm();
              }
            },
            child: Text('保  存'),
            style: ButtonStyle(
                foregroundColor: MaterialStateProperty.all(Colors.white),
                backgroundColor: MaterialStateProperty.all(MyColors.main),
                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(72.w)))),
                textStyle: MaterialStateProperty.all(TextStyle(
                  fontSize: 48.sp,
                  fontWeight: FontWeight.w500,
                ))),
          ),
        )
      ],
    );
  }

  ///保存新建用水户
  _saveForm() async {
    MyDialog.showLoading(msg: '保存采集信息');
    try {
      var params = {
        "project_id": projectInfoId,
        "family_size": familySize.value,
        "phone": phone.value,
        "note": note.value,
        "address": address.value,
        "is_breeder": isBreeder.value,
        "breed_note": breedNote.value,
        "ad_id": adId.value,
        "table_type": meterType.value.value,
        "price_id": NumUtil.getNumByValueDouble(
            NumUtil.getDoubleByValueStr(waterType.value.value), 0) as int,
        "credit_level": waterType.value.creditLevel,
        "table_num":
            meterType.value.value == '1' ? tableNum.value : baseNum.value,
        "init_num": initNum.value,
        "meter_diameter": initNum1.value,
        "username": username.value,
        "identity_card": identityCard.value,
        "base_num": tableNum.value,
        "table_base_id": tableImgId,
        "table_image_id": baseImgId,
        "identity_image_id": identityCardImgId,
      };
      var res = await Http().post(ApiWater.WATER_USER_ADD, data: params);
      ResultModel result = ResultModel.fromJson(res);
      SmartDialog.dismiss();
      if (result.code == 200) {
        SmartDialog.showToast('保存成功!', alignment: Alignment.center);
        WaterUserListPageController waterUserListPageController = Get.find();
        waterUserListPageController.onInit();
        Get.back();
      } else {
        SmartDialog.showToast(result.message, alignment: Alignment.center);
      }
    } catch (e) {
      SmartDialog.showToast('保存失败!', alignment: Alignment.center);
      SmartDialog.dismiss();
    }
  }

  ///基础验证
  _validateForm() {
    var msg = '';
    if (tableNum.value == '') {
      msg = '请填写基表号';
    } else if (initNum.value == '') {
      msg = '请填写水表底数';
    } else if (initNum1.value == '') {
      msg = '请填写水表通径';
    } else if (baseNum.value == '' && meterType.value.value == '2') {
      msg = '请填写采集终端ID';
    } else if (username.value == '') {
      msg = '请填写用户名';
    } else if (identityCard.value == '') {
      msg = '请填写身份证地址';
    }
    if (identityCardImgId == 0) {
      msg = '请上传身份证图片';
    } else if (address.value == '') {
      msg = '请填写详细地址';
    } else if (adId.value == null || adId.value == 0) {
      msg = '请选择行政区划';
    } else if (waterType.value.value == null) {
      msg = '请选择用水类型';
    }
    if (msg != '') {
      SmartDialog.showToast(msg, alignment: Alignment.center);
      return false;
    } else {
      return true;
    }
  }

  ///图片选择器
  final imagePicker = ImagePicker();

  ///打开图片选择器
  openImagePicker() {
    SmartDialog.show(
        alignmentTemp: Alignment.bottomCenter,
        widget: Container(
          height: 451.h,
          width: 1.sw,
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(30.w),
                  topRight: Radius.circular(30.w))),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                height: 130.h,
                alignment: Alignment.center,
                child: Text(
                  '选择操作',
                  style:
                      TextStyle(fontSize: 56.sp, fontWeight: FontWeight.w600),
                ),
              ),
              Expanded(
                  flex: 1,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Container(
                          height: 120.w,
                          width: 120.w,
                          child: InkWell(
                              onTap: () {
                                getImage(
                                    ImageSource.camera, SmartDialog.dismiss);
                              },
                              child: Image(
                                  image: AssetImage(
                                      'assets/images/image_picker/camera.png'),
                                  fit: BoxFit.fill))),
                      SizedBox(
                        width: 287.w,
                      ),
                      Container(
                          height: 120.w,
                          width: 120.w,
                          child: InkWell(
                              onTap: () {
                                getImage(
                                    ImageSource.gallery, SmartDialog.dismiss);
                              },
                              child: Image(
                                  image: AssetImage(
                                      'assets/images/image_picker/gallery.png'),
                                  fit: BoxFit.fill))),
                    ],
                  )),
              InkWell(
                onTap: () {
                  SmartDialog.dismiss();
                },
                child: Container(
                  height: 143.h,
                  width: 100.sw,
                  alignment: Alignment.center,
                  child: Text(
                    '取消',
                    style:
                        TextStyle(fontSize: 40.sp, fontWeight: FontWeight.w500),
                  ),
                  decoration: BoxDecoration(
                      border: Border(
                          top: BorderSide(
                              width: 1.w,
                              color: Color.fromRGBO(221, 221, 221, 1)))),
                ),
              )
            ],
          ),
        ));
  }

  ///选择图片
  Future getImage(ImageSource source, Function callback) async {
    final pickedFile = await ImagePicker.pickImage(source: source);
    if (pickedFile != null) {
      ///压缩图片
      File file = await ImageCompressUtil.imageCompressAndGetFile(pickedFile);
      var bytes = await file.readAsBytes();
      var bs64 = base64Encode(bytes);
      ((activeStep.value == '3') ||
              (activeStep.value == '2' && meterType.value.value == '1'))
          ? checkIdentityCard(bs64, file, callback)
          : checkMeter(bs64, file, callback);
    } else {
      //未选择任何图片
      SmartDialog.showToast('未选择图片', alignment: Alignment.center);
    }
  }

  ///获取百度识别token
  getBaiduToken() async {
    try {
      var result = await Http().get(
        '/baiduApi/oauth/2.0/token',
        data: {
          'grant_type': "client_credentials",
          'client_id': "W9xm7eNjqpeyR6R5GKeALs7b",
          'client_secret': "NV59FAuBnvgTYjYrazagusBxj3B9yhKx",
        },
      );
      baiduToken = result['access_token'];
    } catch (e) {}
  }

  ///百度水表号识别
  checkMeter(data64, pickedFile, Function callback) async {
    MyDialog.showLoading(msg: '识别中...');
    var url = '/baiduApi/rest/2.0/ocr/v1/webimage?access_token=' + baiduToken;
    var res = await Http().postForm(url,
        data: {
          'image': data64,
        },
        options: Options(contentType: 'application/x-www-form-urlencoded'));
    SmartDialog.dismiss();
    try {
      var regResult = null;
      RegExp exp = new RegExp(r"(\d{10,})");
      SystemBaiduNumberResultModel result =
          SystemBaiduNumberResultModel.fromJson(res);
      result.wordsResult.forEach((element) async {
        if (exp.stringMatch(element.words) != null) {
          regResult = exp.stringMatch(element.words);
          switch (activeStep.value) {
            case '1':
              tableNum.value = regResult;
              break;
            case '2':
              baseNum.value = regResult;
              break;
          }

          await uploadPhoto(pickedFile, callback);
        }
      });
      if (regResult == null) {
        SmartDialog.showToast('未检测到数据！', alignment: Alignment.center);
      }
    } catch (e) {
      callback();
      SystemBaiduErrorResultModel result =
          SystemBaiduErrorResultModel.fromJson(res);
      var code = baiduService.errorCode[result.errorCode];
      if (code != null) {
        SmartDialog.showToast(code, alignment: Alignment.center);
      } else {
        SmartDialog.showToast('识别失败！', alignment: Alignment.center);
      }
    }
  }

  ///百度身份证号识别
  checkIdentityCard(data64, pickedFile, Function callback) async {
    MyDialog.showLoading(msg: '识别中...');
    var url = '/baiduApi/rest/2.0/ocr/v1/idcard?access_token=' + baiduToken;
    var res = await Http().postForm(url,
        data: {'image': data64, 'id_card_side': 'front'},
        options: Options(contentType: 'application/x-www-form-urlencoded'));
    SmartDialog.dismiss();
    try {
      var regResult = null;
      SystemBaiduIdentityCardResultModel result =
          SystemBaiduIdentityCardResultModel.fromJson(res);
      username.value = result.wordsResult.name1.words;
      identityCard.value = result.wordsResult.name4.words;
      address.value = result.wordsResult.name3.words;
      await uploadPhoto(pickedFile, callback);
    } catch (e) {
      callback();
      SystemBaiduErrorResultModel result =
          SystemBaiduErrorResultModel.fromJson(res);
      var code = baiduService.errorCode[result.errorCode];
      if (code != null) {
        SmartDialog.showToast(code, alignment: Alignment.center);
      } else {
        SmartDialog.showToast('识别失败！', alignment: Alignment.center);
      }
    }
  }

  final imageList = <ImageModel>[].obs;

  ///上传图片
  ///
  ///[pickedFile]选择的图片
  ///
  ///[callback]回调
  uploadPhoto(pickedFile, Function callback) async {
    String path = File(pickedFile.path).path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
    FormData formData = FormData.fromMap({
      'image_type': suffix,
      'file': await MultipartFile.fromFile(path,
          filename: name, contentType: MediaType.parse("image/$suffix")),
    });
    try {
      MyDialog.showLoading(msg: '上传中...');
      var res = await Http().postForm(ApiBase.FILE_UPLOAD,
          data: formData,
          options: Options(
              contentType: 'multipart/form-data',
              responseType: ResponseType.plain));
      ImageResultModel result = ImageResultModel.fromJson(json.decode(res));
      if (result.code == 200) {
        var imgId = result.content.data.id;
        String imgPath = result.content.data.path;

        if (activeStep.value == '1') {
          tableImgId = imgId;
          tableImgPath.value = imgPath;
          imageList.length == 0
              ? imageList
                  .add(ImageModel(id: tableImgId, path: tableImgPath.value))
              : imageList[0] =
                  ImageModel(id: tableImgId, path: tableImgPath.value);
        } else if (activeStep.value == '2' && meterType.value.value == '2') {
          baseImgId = imgId;
          baseImgPath.value = imgPath;
          imageList.length == 1
              ? imageList
                  .add(ImageModel(id: baseImgId, path: baseImgPath.value))
              : imageList[1] =
                  ImageModel(id: baseImgId, path: baseImgPath.value);
        } else {
          identityCardImgId = imgId;
          identityCardImgPath.value = imgPath;
          imageList.length == 2
              ? imageList.add(ImageModel(
                  id: identityCardImgId, path: identityCardImgPath.value))
              : imageList[2] = ImageModel(
                  id: identityCardImgId, path: identityCardImgPath.value);
        }
        this.update(['stepImage']);
      }
      callback();
      SmartDialog.dismiss();
    } catch (e) {
      print(e);
    }
  }

  ///打开用户基础信息编辑框
  openUserInfoEditPicker() {
    Get.bottomSheet(
      Container(
          height: 0.8.sh,
          width: 1.sw,
          padding: EdgeInsets.fromLTRB(77.w, 53.h, 63.w, 50.h),
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(30.w),
                  topRight: Radius.circular(30.w))),
          child: Column(children: [
            ModalTitle(
                title: '识别信息修改',
                margin: 0,
                onPressed: () {
                  Get.back();
                }),
            Expanded(
                child: Container(
                    width: 1.sw,
                    child: Form(
                      key: _formKeyDetail, //设置globalKey，用于后面获取FormState
                      child: ListView(children: [
                        FormInput(
                          title: '基表号',
                          placeholder: '请输基表号',
                          keyboardType: TextInputType.number,
                          controller:
                              TextEditingController(text: tableNum.value),
                          request: true,
                          onChanged: (value) {
                            tableNum.value = value;
                          },
                        ),
                        FormInput(
                          title: '水表底数',
                          placeholder: '请输水表底数',
                          keyboardType: TextInputType.number,
                          inputFormatters: [InputFormatter.xiaoshu],
                          controller:
                              TextEditingController(text: initNum.value),
                          request: true,
                          onChanged: (value) {
                            initNum.value = value;
                          },
                        ),
                        FormInput(
                          title: '水表通径',
                          placeholder: '请输水表通径',
                          keyboardType: TextInputType.number,
                          inputFormatters: [InputFormatter.xiaoshu],
                          controller:
                              TextEditingController(text: initNum1.value),
                          request: true,
                          unit: 'mm',
                          onChanged: (value) {
                            initNum1.value = value;
                          },
                        ),
                        meterType.value.value == '2'
                            ? FormInput(
                                title: '采集终端ID',
                                placeholder: '请输采集终端ID',
                                keyboardType: TextInputType.number,
                                controller:
                                    TextEditingController(text: baseNum.value),
                                request: true,
                                onChanged: (value) {
                                  baseNum.value = value;
                                },
                              )
                            : Container(),
                        FormInput(
                          title: '姓名',
                          placeholder: '请输姓名',
                          controller:
                              TextEditingController(text: username.value),
                          request: true,
                          onChanged: (value) {
                            username.value = value;
                          },
                        ),
                        FormInput(
                          title: '身份证号',
                          placeholder: '请输身份证号',
                          controller:
                              TextEditingController(text: identityCard.value),
                          request: true,
                          onChanged: (value) {
                            identityCard.value = value;
                          },
                        ),
                        FormInput(
                          title: '住址',
                          placeholder: '请输住址',
                          controller:
                              TextEditingController(text: address.value),
                          request: true,
                          onChanged: (value) {
                            address.value = value;
                          },
                        )
                      ]),
                    )))
          ])),
      backgroundColor: Colors.transparent,
    );
  }
}
